﻿import sys
from PySide6.QtWidgets import (
    QApplication, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget,
    QPushButton, QHBoxLayout, QMessageBox, QInputDialog
)
from PySide6.QtCore import Qt


class DictionaryTree(QWidget):
    def __init__(self, data):
        super().__init__()

        self.tree_widget = QTreeWidget()
        self.tree_widget.setHeaderLabels(["Key", "Value"])
        self.tree_widget.itemChanged.connect(self.on_item_changed)

        # 添加和删除按钮
        self.add_button = QPushButton("添加成员")
        self.delete_button = QPushButton("删除成员")
        self.refresh_button = QPushButton("刷新视图")
        self.add_button.clicked.connect(self.add_item)
        self.delete_button.clicked.connect(self.delete_item)
        self.refresh_button.clicked.connect(self.refresh_tree)

        # 布局
        button_layout = QHBoxLayout()
        button_layout.addWidget(self.add_button)
        button_layout.addWidget(self.delete_button)
        button_layout.addWidget(self.refresh_button)

        layout = QVBoxLayout()
        layout.addWidget(self.tree_widget)
        layout.addLayout(button_layout)
        self.setLayout(layout)

        self.populate_tree(data)

    def populate_tree(self, data, parent=None):
        for key, value in data.items():
            item = QTreeWidgetItem(parent, [str(key), self.format_value(value)])
            item.setFlags(item.flags() | Qt.ItemIsEditable)

            if parent is None:
                self.tree_widget.addTopLevelItem(item)

            if isinstance(value, dict):
                self.populate_tree(value, item)
            elif isinstance(value, list):
                for v in value:
                    list_item = QTreeWidgetItem(item, ["", self.format_value(v)])  # Key can be empty for list items
                    list_item.setFlags(list_item.flags() | Qt.ItemIsEditable)
                    item.addChild(list_item)

    def format_value(self, value):
        if isinstance(value, dict) or isinstance(value, list):
            return str(value)
        return str(value)

    def on_item_changed(self, item, column):
        if column == 0:
            print(f"Key changed to: {item.text(0)}")
        elif column == 1:
            print(f"Value changed to: {item.text(1)}")

    def add_item(self):
        selected_item = self.tree_widget.currentItem()
        if selected_item is not None:
            # 提示用户输入新的键和值
            key, ok1 = QInputDialog.getText(self, '输入键', '键:')
            value, ok2 = QInputDialog.getText(self, '输入值', '值:')

            if ok1 and ok2:
                # 判断值是否是字典或列表
                try:
                    value = eval(value)  # 将字符串解析为字典或列表
                    parent_item = selected_item.parent() if selected_item.parent() else selected_item

                    new_item = QTreeWidgetItem([key, self.format_value(value)])
                    new_item.setFlags(new_item.flags() | Qt.ItemIsEditable)

                    # 添加新项到选中项的同一层级
                    parent_item.addChild(new_item) if selected_item.parent() else self.tree_widget.addTopLevelItem(new_item)

                    # 如果是字典或列表，递归填充子项
                    if isinstance(value, dict) or isinstance(value, list):
                        self.populate_tree({key: value}, new_item)
                except Exception as e:
                    QMessageBox.warning(self, "输入错误", f"无法解析值为字典或列表: {str(e)}")
                    return

            self.refresh_tree()  # 添加后刷新视图
        else:
            QMessageBox.warning(self, "警告", "请先选择一个项目以添加子项。")

    def delete_item(self):
        selected_item = self.tree_widget.currentItem()
        if selected_item is not None:
            if selected_item.parent() is not None:
                selected_item.parent().removeChild(selected_item)
                del selected_item  # 释放内存
            else:
                QMessageBox.warning(self, "警告", "不能删除顶层项。")
        else:
            QMessageBox.warning(self, "警告", "请先选择一个项目以删除。")

    def refresh_tree(self):
        self.tree_widget.update()  # 强制更新树形控件的显示
        print("树形控件已刷新。")


if __name__ == "__main__":
    app = QApplication(sys.argv)

    sample_data = {
        "version": "1.0",
        "description": "WRP环境设置文件",
        "SPACE_DOMAINS": "WRP.BUILD",
        "SPACE_TAGS": [
            "WRP_SHARE_TAG",
            "WRP_SHARE_TAG2"
        ],
        "LOCAL_SPACE_TAGS": [
            "WRP_LOCAL_TAG",
            "WRP_LOCAL_TAG2"
        ],
        "LOCAL_REMARK": "本机备注, 不用分享",
        "wrp_info": {
            "macro_prefix": "wrp"
        },
        "wfc": {
            "macro_prefix": "wfc",
            "com_prj_root": "E:/COMPONENT",
            "com_prj_top": "E:/COM_TOP",
            "app_prj_top": "E:/WFC_APP",
            "app_prj_root": "E:/WFC_APP",
            "main_prj_dir": "${wfc.com_prj_root}/WFC4_MAIN",
            "混合仓_prj_dir": "${wfc.com_prj_root}/WFC4_混合仓",
            "kv_ma_dir": "${wfc.app_prj_root}/KV_MA"
        },
        "lang_module": {
            "python": {
                "version": "3.11",
                "venv": ".\\venv",
                "environment": ".\\environment.yml"
            }
        }
    }

    window = DictionaryTree(sample_data)
    window.setWindowTitle("Dictionary Tree Example")
    window.resize(600, 400)
    window.show()

    sys.exit(app.exec())
